import 'package:dio/dio.dart';
import 'package:jyofservice/bean/xiafa_person_entity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/checkmenu/CheckDetail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:jyofservice/bean/check_data_entity.dart';
import 'package:jyofservice/bean/diao_du_list_entity.dart';
import 'package:jyofservice/generated/json/base/json_convert_content.dart';
import 'package:jyofservice/gongdandiaodu/DiaoDuDetail.dart';
import 'package:jyofservice/gongdandiaodu/GongDanDiaoDu.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/DiaoDuNotification.dart';
import 'package:jyofservice/util/SlideRoute.dart';
import 'package:jyofservice/util/webconfig.dart';

class CheckPge extends StatefulWidget {
  int? functionid;
  CheckPge({this.functionid});
  @override
  _CheckPgeState createState() => _CheckPgeState();
}

class _CheckPgeState extends State<CheckPge> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  ScrollController scrollController = ScrollController();

  List<CheckDataData> checkListData = [];
  TextEditingController ideaController = TextEditingController();
  int page = 1;
  String? wherestr = "1=1";
  bool isloading = false;
  bool isAllCheck = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkListData.clear();
    getCheckListData();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        print('滑动到了最底部');
        page++;
        getCheckListData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener<DiaoDuNotification>(
      onNotification: (notification) {
        isloading = false;
        if (mounted) {
          setState(() {
            checkListData.clear();
            page = 1;
            wherestr = notification.wherestr;
            getCheckListData();
          });
        }
        return true;
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          centerTitle: true,
          title: Text(widget.functionid == 0 ? '确认工单' : '工单转交',
              //FluroConvertUtils.fluroCnParamsDecode(widget.title),
              style: TextStyle(
                  color: Colors.white, fontSize: ScreenUtil().setSp(45))),
        ),
        body: Container(
          color: const Color(0xFFF1F1F1),
          child: Column(
            children: <Widget>[
              /*
              //确认与退回3-1
              widget.functionid==0?
              Row(
                  children: <Widget>[
                    Checkbox(
                        value: isAllCheck,
                        onChanged: (bool val) {
                          this.setState(() {
                            this.isAllCheck = !this.isAllCheck;
                            for (int i = 0; i < checkListData.length; i++) {
                              checkListData[i].isSelect = isAllCheck;
                            }
                          });
                        }),
                    Text('全选')
                  ],
                ):SizedBox(
                height: ScreenUtil().setHeight(1),
              ),
              */

              Expanded(
                  child: Stack(
                alignment: Alignment(0.5, 0.5),
                children: <Widget>[
                  RefreshIndicator(
                      child: ListView.builder(
                        physics: AlwaysScrollableScrollPhysics(),
                        controller: scrollController,
                        itemBuilder: (context, item) {
                          return buildListData(
                              context,
                              item,
                              checkListData[item].lSH,
                              checkListData[item].createDate!,
                              checkListData[item].importName!,
                              checkListData[item].describe,
                              checkListData[item].stateName!,
                              checkListData[item].ifyq,
                              checkListData[item].gdTypeId,
                              checkListData[item].typeName!,
                              checkListData[item].allName,
                              checkListData[item].isjdyq!,
                              checkListData[item].jdsx_time);
                        },
                        itemCount: checkListData.length,
                      ),
                      onRefresh: _onRefresh),
                  Offstage(
                    offstage: isloading,
                    child: SpinKitFadingCircle(
                      color: Colors.blue,
                      size: 50.0,
                    ),
                  )
                ],
              )),
              /*
             //确认与退回3-2
             widget.functionid==0?
             Row(
               children: [
                 Expanded(child: GestureDetector(
                   onTap: () {
                     String ids = "";

                     for (int i = 0; i < checkListData.length; i++) {
                       if (checkListData[i].isSelect) {
                         ids += checkListData[i].lSH.toString() + ",";
                       }
                     }
                     if (ids.length < 1) {
                       Fluttertoast.showToast(
                           msg: "请至少选择一个",
                           toastLength: Toast.LENGTH_LONG,
                           textColor: Colors.white,
                           backgroundColor: Colors.black87,
                           gravity: ToastGravity.BOTTOM);
                       return;
                     }
                     showAlert(
                         "是否将选中工单进行确认？", ids.substring(0, ids.length - 1));
                   },
                   child: Container(
                     decoration: BoxDecoration(
                         border: Border.all(color: Colors.white),
                         color: Colors.blue),
                     height: ScreenUtil().setHeight(100),
                     width: ScreenUtil.screenWidth,
                     child: Center(
                       child: Text(
                         '确认工单',
                         style: TextStyle(color: Colors.white),
                       ),
                     ),
                   ),
                 )),
                 Expanded(child: GestureDetector(
                   onTap: () {
                     String ids = "";

                     for (int i = 0; i < checkListData.length; i++) {
                       if (checkListData[i].isSelect) {
                         ids += checkListData[i].lSH.toString() + ",";
                       }
                     }
                     if (ids.length < 1) {
                       Fluttertoast.showToast(
                           msg: "请至少选择一个",
                           toastLength: Toast.LENGTH_LONG,
                           textColor: Colors.white,
                           backgroundColor: Colors.black87,
                           gravity: ToastGravity.BOTTOM);
                       return;
                     }
                     showAlertBack(ids.substring(0, ids.length - 1));
                   },
                   child: Container(
                     decoration: BoxDecoration(
                         border: Border.all(color: Colors.blue),
                         color: Colors.blue),
                     height: ScreenUtil().setHeight(100),
                     width: ScreenUtil.screenWidth,
                     child: Center(
                       child: Text(
                         '退回工单',
                         style: TextStyle(color: Colors.white),
                       ),
                     ),
                   ),
                 ))
               ],
             ):Container()
             */
            ],
          ),
        ),
      ),
    );
  }

  void showAlertBack(String ids) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text("退回原因"),
            content: Container(
              height: ScreenUtil().setHeight(120),
              child: TextField(
                controller: ideaController,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  //字母间距
                  letterSpacing: 0.5,
                  color: const Color(0xFF4A4A4A),
                ),
                decoration: InputDecoration(
                  hintStyle: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenUtil().setSp(28.0)),
                  hintText: "请输入退回原因",
                ),
              ),
            ),
            actions: <Widget>[
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.black12)),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.blueAccent)),
                  onPressed: () {
                    if (ideaController.text.toString().length > 0) {
                      Navigator.pop(context);
                      delay(ids);
                    } else {
                      Fluttertoast.showToast(msg: '退回原因不能为空');
                    }
                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
        });
  }

  // 返回每个隐藏的菜单项
  SelectView(String text, String id) {
    return PopupMenuItem<String>(
      value: id,
      child: Text(text),
    );
  }

  //刷新
  Future _onRefresh() async {
    page = 1;
    checkListData.clear();
    wherestr = "1=1";
    getCheckListData();
  }

  Widget buildListData(
      BuildContext context,
      int i,
      String? lsh,
      String createDate,
      String importName,
      String? describe,
      String stateName,
      String? ifyq,
      int? typeid,
      String typeName,
      String? allName,
      String isjdyq,
      String? jdsx_time) {
    return Container(
      child: GestureDetector(
        child: Row(
          children: <Widget>[
            Expanded(
                child: Stack(
              alignment: Alignment(0.9, -1),
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 11),
                  color: Colors.white,
                  width: ScreenUtil().screenWidth,
                  height: ScreenUtil().setHeight(450),
                  child: Row(
                    children: <Widget>[
                      Stack(
                        alignment: Alignment.center,
                        children: <Widget>[
                          Image.asset(
                            'images/juxing2kaobei24.png',
                            fit: BoxFit.fill,
                            width: ScreenUtil().setWidth(160),
                            height: ScreenUtil().setHeight(450),
                          ),
                          Text(
                            getTypeName(typeName),
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: ScreenUtil().setSp(47)),
                          ),
                        ],
                      ),
                      Expanded(
                        flex: 1,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.fromLTRB(5, 5, 0, 5),
                                  child: Text(
                                    '工单编号:',
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(32),
                                        color: Colors.black87),
                                  ),
                                ),
                                Expanded(
                                  child: Padding(
                                    padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                                    child: Text(
                                      '$lsh',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(32),
                                          color: Colors.black87),
                                    ),
                                  ),
                                )
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.fromLTRB(5, 5, 0, 5),
                                  child: Text(
                                    '住户地址:',
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(32),
                                        color: Colors.black87),
                                  ),
                                ),
                                Expanded(
                                  child: Padding(
                                    padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                                    child: Text(
                                      '$allName',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(32),
                                          color: Colors.black87),
                                    ),
                                  ),
                                )
                              ],
                            ),
                            Padding(
                              padding: EdgeInsets.all(5),
                              child: Text(
                                '下单时间:' + createDate ?? "",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32),
                                    color: Colors.black87),
                              ),
                            ),
                            Offstage(
                              offstage: jdsx_time == null ? true : false,
                              child: Padding(
                                padding: EdgeInsets.all(5),
                                child: Row(
                                  children: [
                                    Text(
                                      '接单时限:${jdsx_time == null ? "" : jdsx_time + "小时"}',
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(32),
                                          color: Colors.black87),
                                    ),
                                    SizedBox(
                                      width: 20,
                                    ),
                                    Text(
                                      '是否超时:' + isjdyq ?? "",
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(32),
                                          color: isjdyq == '是'
                                              ? Colors.redAccent
                                              : Colors.black87),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.all(5),
                                  child: Text(
                                    '紧急程度:' + importName ?? "",
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(32),
                                        color: Colors.red),
                                  ),
                                ),
                              ],
                            ),
                            Container(
                              width: ScreenUtil().screenWidth,
                              height: ScreenUtil().setHeight(2),
                              color: Colors.grey,
                            ),
                            SizedBox(
                              height: ScreenUtil().setHeight(20),
                            ),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                Expanded(
                                    flex: 1,
                                    child: Padding(
                                      padding: EdgeInsets.only(left: 5),
                                      child: Text(
                                        describe ?? "",
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            color: stateName == "处理中"
                                                ? Colors.blue
                                                : stateName == "未接单"
                                                    ? Colors.red
                                                    : Colors.green,
                                            fontSize: ScreenUtil().setSp(40),
                                            fontWeight: FontWeight.bold),
                                      ),
                                    )),
                                Image.asset(
                                  stateName == "处理中"
                                      ? 'images/daichuli.png'
                                      : stateName == "未接单"
                                          ? 'images/weijiedan.png'
                                          : 'images/yichulikaobei.png',
                                  width: ScreenUtil().setWidth(45),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(right: 5),
                                  child: Text(
                                    stateName,
                                    style: TextStyle(
                                      color: stateName == "处理中"
                                          ? Colors.blue
                                          : stateName == "未接单"
                                              ? Colors.red
                                              : Colors.green,
                                      fontSize: ScreenUtil().setSp(35),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(
                              height: ScreenUtil().setHeight(10),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Offstage(
                  offstage: ifyq == "是" ? false : true,
                  child: Image.asset(
                    'images/yuqi.png',
                    width: ScreenUtil().setWidth(70),
                  ),
                )
              ],
            )),
            /*
            ////确认与退回3-3
            widget.functionid==0?
           Container(
                color: Colors.white,
                margin: EdgeInsets.only(top: 11),
                height: ScreenUtil().setHeight(420),
                child: Checkbox(
                    value: checkListData[i].isSelect,
                    onChanged: (bool val) {
                      bool flag = true;
                      print("haha");
                      checkListData[i].isSelect = val;
                      if (isAllCheck) {
                        if (!val) {
                          isAllCheck = false;
                        }
                      } else {
                        for (int i = 0; i < checkListData.length; i++) {
                          if (!checkListData[i].isSelect) {
                            flag = false;
                            break;
                          }
                        }
                        if (flag) {
                          isAllCheck = true;
                        }
                      }

                      if (mounted) {
                        setState(() {});
                      }
                    }),
              ):Container()
            */
          ],
        ),
        onTap: () {
          Navigator.push(context, new MaterialPageRoute(builder: (context) {
            return CheckDetail(
              LSH: lsh,
              is0ffstage: true,
              //是否接单超时 是和否
              isjdyq: isjdyq,
              //接单时限
              jdsxTime: jdsx_time,
              view: "GetMyAndChildrenAllWorkForm",
              isDeliver:
                  widget.functionid == 0 ? false : true, //false确认工单 true转交工单
            );
          })).then((value) {
            page = 1;
            checkListData.clear();
            getCheckListData();
          });
        },
      ),
    );
  }

  String getTypeName(String typeName) {
    String result = "";

    for (int i = 0; i < typeName.length; i++) {
      if (i != typeName.length - 1) {
        String str = typeName.substring(i, i + 1);
        result += str + "\n";
      } else {
        String str = typeName.substring(i, i + 1);
        result += str;
      }
    }
    return result;
  }

  Future getCheckListData() async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "view": "GetMySelfWaitDoWork",
      "wherestr": "1=1",
      "limit": 10,
      "page": page,
      "sortName": "CreateDate",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    Response response = await Dio()
        .post(WebConfig().baseUrl + "DB/postrowdataforlayui", data: data);
    print(response.data.toString());

    if (response.data["code"] == 0) {
      CheckDataEntity? diaoDuListEntity = CheckDataEntity().fromJson(response.data);
      if(diaoDuListEntity?.data != null){
        for (int i = 0; i < diaoDuListEntity!.data!.length; i++) {
          CheckDataData serviceRecordData = diaoDuListEntity.data![i]!;
          serviceRecordData.isSelect = false;
          checkListData.add(serviceRecordData);
        }
      }
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
    }
    isloading = true;
    if (mounted) {
      setState(() {});
    }
  }

  //确认工单提示框
  void showAlert(String msg, String id) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text(msg),
            actions: <Widget>[
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.black12)),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.blueAccent)),
                  onPressed: () {
                    Navigator.pop(context);
                    goCheckMenu(id);
                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
        });
  }

  Future goCheckMenu(String ids) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "LSH": ids,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/NiBuShiZhenZhengDeKuaiLe",
        data: data);
    print(response.data.toString());

    if (response.data["Code"] == "200") {
      Fluttertoast.showToast(msg: "操作成功");
      page = 1;
      checkListData.clear();
      getCheckListData();
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
    }
  }

  //退回工单
  Future delay(String ids) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    String aesData = await AesUtil.encodeBase64();
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    var data = {
      "key": key,
      "LSH": ids,
      "Reason": ideaController.text.toString(),
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio()
        .post(WebConfig().baseUrl + "Work/RequestHuanBan", data: data);
    if (mounted) {
      setState(() {
        isloading = true;
      });
    }
    if (response.data["Code"] == "200") {
      Fluttertoast.showToast(msg: "提交成功");
      page = 1;
      checkListData.clear();
      getCheckListData();
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
    }
  }
}
